// 为了方便管理请求接口，所有的请求都以异步 action 的方式进行封装
import http from '@/utils/request'
import { setTokenInfo } from '@/utils/storage'
import { AppDispatch } from '../index'
import { Profile } from '../reducer/user'
import { UserAction } from '../reducer/user'
/**
 * 发送短信验证码
 * @param mobile
 * @returns
 */
export const sendCodesAPI = (mobile: string) => {
  return (dispatch: AppDispatch) => {
    http.get(`/v1_0/sms/codes/${mobile}`)
  }
}

/**
 * 用户认证（登录注册）
 * @param param0  { mobile: string code: string }
 * @returns
 */
type loginType = {
  mobile: string
  code: string
}
export const loginAPI = ({ mobile, code }: loginType) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.post('/v1_0/authorizations', { mobile, code })
    // 保存到 Redux 中
    dispatch({ type: 'user/saveToken', payload: res.data })
    // 保存到本地
    setTokenInfo(res.data)
  }
}

/**
 * 清除 Token
 * @returns
 */
export const clearTokenAPI = (): UserAction => {
  return { type: 'user/clearToken' }
}

/**
 * 获取用户自己信息
 * @returns
 */
export const getUserInfoAPI = () => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get('/v1_0/user')
    // console.log('/v1_0/user', res)
    dispatch({ type: 'user/saveUserInfo', payload: res.data })
  }
}

/**
 * 获取用户个人资料
 * @returns
 */
export const getProfileAPI = () => {
  return async (dispatch: AppDispatch) => {
    const res = await http.get('/v1_0/user/profile')
    dispatch({ type: 'user/saveProfile', payload: res.data })
  }
}

/**
 * 编辑用户照片资料（头像、身份证照片）
 * @param data FormData
 * @returns
 */
export const editUserPtotoAPI = (data: FormData) => {
  return async (dispatch: AppDispatch) => {
    const res = await http.patch('/v1_0/user/photo', data)
    dispatch({ type: 'user/updateProfile', payload: res.data })
  }
}

/**
 * 编辑更新用户个人资料
 * @param data
 * @returns
 */
export const updateProfileAPI = (data: Partial<Profile>) => {
  return async (dispatch: AppDispatch) => {
    await http.patch('/v1_0/user/profile', data)
    dispatch({ type: 'user/updateProfile', payload: data })
  }
}
